<template>
	<view class="bugBox">
		<!-- <view class="from_list" v-if="agentInfo.UserName">
			<view class="from_item">
				<text class="label" style="font-size: 36rpx;font-weight: 600;">所属代理</text>
				<view class="input"></view>
			</view>
			<view class="from_item">
				<text class="label">代理名称</text>
				<view class="input">{{ agentInfo.UserName }}</view>
			</view>
			<view class="from_item" @click="telFun(agentInfo.Phone)">
				<text class="label">代理电话</text>
				<view class="input">{{ agentInfo.Phone }}</view>
				<image class="phonePic" src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/upload/1729586627953619.png" mode="widthFix" />
				
			</view>
		</view> -->
		<view class="from_list" style="width:100%;padding-bottom:0;">
			<image style="width:100%" src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/upload/1731308675263218.jpg"
				mode="widthFix" />
		</view>
		<view class="from_list">
			<view class="from_item" v-for="(item, index) in list" :key="index">
				<text class="label"
					:class="{ 'requiredClass': item.required, 'textareaLabel': item.label == '门店描述' }">{{
						item.label }}</text>
				<input v-model="item.value" class="input" v-if="item.type == 'text' || item.type == 'number'"
					:placeholder="item.placeholder" :type="item.type" />
				<textarea style="height: 140rpx;padding:0;" cols="10" rows="5" v-model="item.value" class="input"
					v-if="item.type == 'textArea'" :placeholder="item.placeholder"
					placeholder-style='padding:0rpx;'></textarea>
				<view class="hiddenText" style="flex: 1; text-align: left;" v-if="item.type == 'loc'"
					@click="chooseLocation">
					{{ item.value ? item.value : item.placeholder }}
				</view>
				<view class="select_type" v-if="item.type == 'select'" @click="selectType">
					<text>{{ item.value }}</text>
					<image src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/arror_right.png" mode=""></image>
				</view>
			</view>
			<!-- <view class="from_item border_b">
				<text class="label requiredClass">营业时间</text>
				<text class="input" @tap="showPicker"> {{timeRanges||'请选择营业时间'}} </text>
				<tpf-time-range ref="time" :startTime="startTime" :startDefaultTime="startDefaultTime"
					:endTime="endTime" :endDefaultTime="endDefaultTime" @timeRange="timeRange">
				</tpf-time-range>
			</view> -->
			<!-- 上传图片 -->
			<view class="upload">
				<text>门店照片(如门头、门店内照片)</text>
				<view class="img_box">
					<view class="img" v-for="(item, i) in imgArr" :key="i">
						<image :src="item.tempUrl" mode="aspectFill"></image>
						<view class="icon" @click.stop="delImg(i)">
							<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1710154762492571.png"
								mode=""></image>
						</view>
					</view>
					<view class="img addimg" @tap="upload" v-if="imgArr.length < 3">
						<image src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/upload.png" mode="">
						</image>
					</view>
				</view>
			</view>
			<view class="button_view">
				<button @click="submit">确定开通（¥ {{ agentInfo.AfmaPrice || '开通账号' }}）</button>
			</view>
		</view>
		<u-picker :show="show" :columns="columns" @confirm="confirm"></u-picker>
	</view>
</template>

<script>
import util from '@/common/util'
const env = require('@/common/ossutil/config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;
export default {
	data() {
		return {
			startTime: "00:00",
			startDefaultTime: "00:00",
			endTime: "24:00",
			endDefaultTime: "00:00",
			list: [{
				label: '联系人',
				value: '',
				placeholder: '请输入姓名',
				type: 'text',
				required: true,
			},
			{
				label: '联系电话',
				value: '',
				placeholder: '请输入电话',
				type: 'number',
				required: true,
			},
			{
				label: '门店名称',
				value: '',
				placeholder: '请输入门店名称',
				type: 'text',
				required: true,
			},
			// {
			// 	label: '门店类型',
			// 	value: '其它',
			// 	placeholder: '',
			// 	type: 'select'
			// },
			{
				label: '门店位置',
				value: '',
				placeholder: '点击定位获取',
				type: 'loc',
				latitude: '',
				longitude: '',
				province: '',
				city: '',
				required: true,
			},
			{
				label: '门店描述',
				value: '',
				placeholder: '请输入门店描述',
				type: 'textArea',
				required: false,
			},
			],
			columns: [
				['大学内或周边打印店', '中小学周边打印店', '政府周边打印店', '其他']
			],
			// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
			radiovalue1: '',
			show: false,
			imgArr: [],
			timeRanges: '',
			daiLiID: null,
			accountPrice: 0,
			userInfo: null,
			agentInfo: null,
		}
	},
	async onLoad(e) {
		console.log(e, 'eee');

		if (e?.scene) {
			this.daiLiID = e?.scene
			await this.bindAgent(e?.scene)
		}
		this.userInfo = uni.getStorageSync('user')
		this.list[1].value = this.userInfo?.Phone
		this.getAgentInfo()

	},
	methods: {
		// 绑定代理商账号
		async bindAgent(id) {
			let that = this
			const res = await that.$api.post('AgentOperate/SetProxyBinding', { DaiLiID: id });
			if (res.code == 109) {
				uni.showLoading({
					title: '加载中'
				});
				setTimeout(async () => {
					if (that.daiLiID) {
						await this.bindAgent(that.daiLiID)
					}
					that.userInfo = uni.getStorageSync('user')
					that.list[1].value = that.userInfo?.Phone
					that.getAgentInfo()
					that.bindAgent(that.daiLiID)
					uni.hideLoading()
				}, 1500);

				return
			}
			if (res.code != 0) {
				uni.showModal({
					title: '提示',
					content: '您已绑定其他代理，不能再绑定该代理。',
					showCancel: false,
					confirmText: '返回首页',
					success: function (res) {
						if (res.confirm) {
							that.nav_to('/pages/tab/home')
						}
					}
				});
			}
			that.getAgentInfo()
		},
		// 获取当前代理商信息
		async getAgentInfo() {
			const that = this
			const res = await that.$api.post('Afma/GetAccount');
			that.agentInfo = res?.data

		},
		showPicker() {
			this.$refs['time'].open();
		},
		timeRange(e) {
			this.timeRanges = e.join('-')
			console.log(e);
		},
		confirm(e) {
			console.log('confirm', e)
			this.show = false
			const index = this.list.findIndex(item => item.type === 'select');
			this.list[index].value = e.value[0]
		},
		async submit() {
			const that = this

			// 提取 netPath，并生成以逗号分隔的字符串
			const netPaths = this.imgArr
				.filter(item => item.netPath) // 过滤掉没有 netPath 的项
				.map(item => item.netPath) // 提取 netPath
				.join(','); // 连接成逗号分隔的字符串

			// 验证所有必填字段不能为空
			const requiredFields = {
				ShopName: this.list[2].value,
				Address: this.list[3].value,
				Longitude: this.list[3].longitude,
				Latitude: this.list[3].latitude,
				ServerPhone: this.list[1].value,
				Contacts: this.list[0].value,
				// Description: this.list[4].value,
				Province: this.list[3].province,
				City: this.list[3].city,
				// BusinessHours: this.timeRanges
			};

			for (const [key, value] of Object.entries(requiredFields)) {
				if (value === undefined || value === null || value === '') {
					uni.showToast({
						title: `请完善表格`,
						icon: 'none'
					})
					return
				}
			}

			// 验证 ServerPhone 是否符合电话号码格式
			const phoneRegex = /^[0-9]{10,15}$/; // 可以根据需要调整正则表达式
			if (!phoneRegex.test(requiredFields.ServerPhone)) {
				uni.showToast({
					title: `请输入正确的手机号`,
					icon: 'none'
				})
				return
			}

			// 构造要发送的对象
			const obj = {
				ShopImgs: netPaths,
				ShopName: requiredFields.ShopName,
				Address: requiredFields.Address,
				Longitude: requiredFields.Longitude,
				Latitude: requiredFields.Latitude,
				ServerPhone: requiredFields.ServerPhone,
				Status: 0,
				Contacts: requiredFields.Contacts,
				Guid: uni.getStorageSync('guid'),
				Description: this.list[4].value || '',
				Province: requiredFields.Province,
				City: requiredFields.Province,
				BusinessHours: requiredFields.BusinessHours,
			};
			const res = await this.$api.post('Afma/SetApplyAccount', {
				...obj
			});
			if (res?.code == 0) {
				let payObj = res?.data;
				if (this.agentInfo.AfmaPrice == 0) {
					that.$pv.msg('开通成功');
					setTimeout(() => {
						// that.nav_to('/pages/tab/my')
						that.nav_to('/pages/otherPage/manage?isPayNow=true')
					}, 1000);
					return
				}
				uni.requestPayment({
					provider: 'wxpay',
					// #ifdef APP
					orderInfo: payObj,
					// #endif
					// #ifdef MP-WEIXIN
					timeStamp: payObj.timeStamp,
					nonceStr: payObj.nonceStr,
					package: payObj.package,
					signType: payObj.signType,
					paySign: payObj.paySign,
					// #endif
					success: async function (res) {
						that.$pv.msg('支付成功');
						setTimeout(() => {
							// that.nav_to('/pages/tab/my')
							that.nav_to('/pages/otherPage/manage?isPayNow=true')
						}, 1000);


					},
					fail: function (err) {
						that.$pv.msg('您已取消支付');

					}
				});

			} else {
				this.$pv.msg(res?.message)
			}



		},
		async uploading(url, tempKey) {
			console.log('url ----------' + url);

			const r = await this.$upload(url, (pro) => {
				this.imgArr.forEach((item) => {
					if (item.tempKey == tempKey) {
						item.pro = pro;
					}
				});
			});
			this.imgArr.forEach((item) => {
				if (item.tempKey == tempKey) {
					item.netPath = r;
				}
			});

			console.log('upload file ' + r);
			// this.formdata.PhotoUrl.push(r);
			// this.formdata.PhotoUrl = r
		},
		upload() {
			let _this = this;
			let diyCount = 3 - this.imgArr.length
			uni.chooseMedia({
				count: diyCount,
				mediaType: ['image'],
				sourceType: ['album', 'camera'],
				maxDuration: 30,
				camera: 'back',
				success(res) {
					console.log(res);
					res.tempFiles.forEach(async (item) => {
						let o = {
							duration: 0,
							fileType: item.fileType,
							tempUrl: item.tempFilePath,
							flieUrl: item.tempFilePath,
							tempKey: uni.$u.guid(8),
							pro: 0,
						};

						_this.imgArr.push(o);

						let rex = await _this.uploading(o.flieUrl, o.tempKey);
						console.log('rex-------', rex);
					});
				},
			});
		},
		delImg(i) {
			this.imgArr.splice(i, 1);
			// this.formdata.Images.splice(i, 1);
		},

		resetType() {
			this.radiovalue1 = ''
			const index = this.list.findIndex(item => item.type === 'select');
			this.list[index].value = ''
		},
		selectType() {
			this.show = true
		},
		chooseLocation() {
			let that = this
			uni.chooseLocation({
				async success(res) {
					let res2 = await util.getAddress(res)
					console.log(res2);
					const index = that.list.findIndex(item => item.type === 'loc');
					console.log(index);
					console.log(res);
					that.list[index].value = res.address
					that.list[index].latitude = res.latitude
					that.list[index].longitude = res.longitude
					that.list[index].province = res2.result.address_component.province
					that.list[index].city = res2.result.address_component.city

				},
				fail(err) {
					console.log(err);
				}
			})
		},
		radioChange(n) {
			const index = this.list.findIndex(item => item.type === 'select');
			this.list[index].value = n
		},
		telFun(tel) {
			uni.makePhoneCall({
				phoneNumber: tel,
				success() {
					console.log('拨号成功');
				},
				fail(err) {
					console.error('拨号失败:', err);
				},
			});
		},
	}
}
</script>
<style>
page {
	background-color: #f6f6f6;
}
</style>

<style lang="scss" scoped>
.bugBox {
	padding-bottom: 170rpx;
}

.img:nth-child(3n) {
	margin-right: 0;
}

.addimg {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #F6F6F6;

	image {
		width: 80rpx;
		height: 80rpx;
	}
}

.img_box {
	display: flex;
	align-items: center;
	// justify-content: space-evenly;
	flex-wrap: wrap;
	margin-top: 20rpx;
}

.videobox {
	padding: 32rpx;
	position: relative;

	>view {
		width: 100%;
		height: 300rpx;
		border-radius: 16rpx;
		overflow: hidden;

		video {
			width: 100%;
			height: 100%;
		}
	}

	.icon {
		position: absolute;
		right: 10rpx;
		top: 10rpx;
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		// border-radius: 50%;
		z-index: 9;

		image {
			width: 40rpx;
			height: 40rpx;
			background: #fff;
			border-radius: 50%;
		}
	}
}

.img {
	width: 200rpx;
	height: 200rpx;
	border-radius: 8rpx;
	margin-right: 16rpx;
	margin-top: 16rpx;
	// overflow: hidden;
	position: relative;

	image {
		border-radius: 8rpx;
		width: 100%;
		height: 100%;
	}

	.icon {
		position: absolute;
		right: -20rpx;
		top: -14rpx;
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		// border-radius: 50%;
		z-index: 9;

		image {
			width: 40rpx;
			height: 40rpx;
			background: #fff;
			border-radius: 50%;
		}
	}
}

.img:nth-child(3n) {
	margin-right: 0;
}

.addimg {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #F6F6F6;

	image {
		width: 80rpx;
		height: 80rpx;
	}
}

.button_view {
	position: fixed;
	bottom: 80rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 80%;
	z-index: 99;

	button {
		color: white;
		background: #3572FE;
		border-radius: 15rpx;
		margin-right: 24rpx;
	}
}

.upload {
	padding: 20rpx;
	margin-top: 20rpx;
	background-color: #fff;
	border-radius: 16rpx;
}

.button_group {
	display: flex;
	align-items: center;

	button {
		width: 50%;
		display: flex;
		align-items: center;
		font-size: 28rpx;
		justify-content: center;
	}
}

.popup_container {
	padding: 30rpx;

	.type {
		height: 80rpx;
		display: flex;
		// align-items: center;
	}
}

.input {
	flex: 1;
}

.choose_location {
	width: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 1rpx solid #3572fe;
	border-radius: 30rpx;
	height: 50rpx;

	text {
		color: #3572fe;
		font-size: 28rpx
	}
}

.select_type {
	display: flex;
	align-items: center;
	font-size: 24rpx;

	image {
		width: 25rpx;
		height: 25rpx;
	}
}

.label {
	min-width: 150rpx;
	position: relative;

}

.requiredClass {
	::after {
		position: absolute;
		content: '*';
		top: -10rpx;
		left: -26rpx;
		color: red;
	}
}

.textareaLabel {
	margin-bottom: auto;
	padding-top: 16rpx;
}



.from_list {
	padding: 24rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;

	.from_item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 40rpx;
		min-height: 120rpx;
		border-bottom: 1rpx solid #eeeeee;
		background-color: #fff;
		position: relative;

		&:nth-of-type(1) {
			border-radius: 16rpx 16rpx 0 0;
		}

		>textarea {
			padding: 0 !important;
		}

		.phonePic {
			position: absolute;
			width: 48rpx;
			height: 48rpx;
			top: 50%;
			right: 55rpx;
			transform: translateY(-50%);
		}

	}


}

.border_b {
	border-radius: 0 0 16rpx 16rpx;
}
</style>